package rpc.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.netty.tcp.entity.RpcMessage;
import rpc.serialize.SerializeUtils;

/*********
 *
 *
 * @author 197
 * @date 2020/6/19 18:10
 *
 **/

public class RpcMessageEncoder extends MessageToByteEncoder<RpcMessage> {

  private static final Logger logger = LoggerFactory.getLogger(RpcMessageEncoder.class);

  @Override
  protected void encode(ChannelHandlerContext ctx, RpcMessage msg, ByteBuf out) throws Exception {
//		logger.info(" encode msg:{}", msg);
    if (Objects.nonNull(msg)) {
      byte[] serialize = SerializeUtils.serialize(msg);
      out.writeByte(RpcMessage.getFlag());
      out.writeInt(serialize.length);
      out.writeBytes(serialize);
    }

//		logger.info(" encoded msg:{}", msg.getMsgId());
  }

}
